package com.gofunbuy.app.store;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.gofunbuy.R;
import com.gofunbuy.TabHomeGroup;
import com.gofunbuy.TabMemberGroup;
import com.gofunbuy.TabStoreGroup;
import com.gofunbuy.app.member.SubMemberDocumentActivity;
import com.gofunbuy.app.member.SubMemberFavorableDetailActivity;
import com.gofunbuy.app.member.SubMemberLoginActivity;
import com.gofunbuy.app.member.SubMemberRegistActivity;
import com.gofunbuy.app.member.SubMemberTelCardActivity;
import com.gofunbuy.core.ProductAdEntity;
import com.gofunbuy.core.ProductClassEntity;
import com.gofunbuy.core.ProductEntity;
import com.gofunbuy.http.HttpClientImpl;
import com.gofunbuy.util.AsyncImageLoader;
import com.gofunbuy.util.GoFunBuyUtils;
import com.gofunbuy.util.XmlUtil;
import com.gofunbuy.util.AsyncImageLoader2.ImageCallback;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class TabStoreActivity extends Activity implements OnClickListener {
	
	//private AsyncImageLoader asyncImageLoader;
	private ProgressBar mProgressBar;
	private ListView mProductList;
	private AppProductAdapter mAdapter;
	private List<ProductEntity> products;
	private List<ProductAdEntity> ads;
	private List<ProductClassEntity> classes;
	Map<String,List<ProductEntity>> pro ;
	private MyAdapter mAdAdapter;
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private List<View> dots; // 图片标题正文的那些点
	private TextView tvTitle;
	private LinearLayout mClasses;
	private int currentItem = 0; // 当前图片的索引号
	private ScheduledExecutorService scheduledExecutorService;
	public static ProductEntity currentProduct;
	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			/*if(currentItem>=imageViews.size()){
				currentItem = 0;
				viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
				return;
			}*/
			viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_layout);
		//asyncImageLoader = new AsyncImageLoader();
		init();
		
		 new LoadTask().execute();				
	}
	private List<ProductClassEntity> getProductsClasses(){
		String uri = "http://www.eye4gift.com/gofun/app_get_sort.php";
		String userId = GoFunBuyUtils.mUserID==null?"0":GoFunBuyUtils.mUserID;	
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("shopcode", "goinside");
		params.put("userid", userId);
		InputStream is = HttpClientImpl.HttpPostData2(uri, params);
		List<ProductClassEntity> products = XmlUtil.getProductClassList(is);		
		return products;
	}
	private List<ProductAdEntity> getProductAd(){
		String uri = "http://www.eye4gift.com/gofun/app_get_product_ad.php";
		String userId = GoFunBuyUtils.mUserID==null?"0":GoFunBuyUtils.mUserID;	
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("shopcode", "goinside");
		params.put("userid", userId);
		InputStream is = HttpClientImpl.HttpPostData2(uri, params);
		List<ProductAdEntity> ads = XmlUtil.getProductAdList(is);		
		return ads;
	}
	private List<ProductEntity> getProducts(){
		String uri = "http://www.eye4gift.com/gofun/app_get_product.php";
		String userId = GoFunBuyUtils.mUserID==null?"0":GoFunBuyUtils.mUserID;	
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("shopcode", "goinside");
		params.put("userid", userId);
		InputStream is = HttpClientImpl.HttpPostData2(uri, params);
		List<ProductEntity> products = XmlUtil.getProductList(is);		
		return products;
	}
	
	private void init(){
		
		TextView back = (TextView)findViewById(R.id.store_topbar_back);
		back.setVisibility(View.GONE);
		
		tvTitle = (TextView) findViewById(R.id.store_topbar_title);
		tvTitle.setText(R.string.title_network_store);
		
		TextView buyList = (TextView) findViewById(R.id.store_topbar_buylist);
		buyList.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(SubTabStoreOrderActivity.class);
			}			
		});
		
		mProductList = (ListView)findViewById(R.id.store_product_list);
		mAdapter = new AppProductAdapter(this,mProductList);
		mProductList.setAdapter(mAdapter);
		mProductList.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
				currentProduct =  products.get(arg2);
				startActivity(SubTabStoreProductDetailActivity.class);
			}
			
		});
		mProgressBar = (ProgressBar)findViewById(R.id.store_progress);
		
		mClasses = (LinearLayout)findViewById(R.id.store_product_classes);
		
		mAdAdapter = new MyAdapter();				
		imageViews = new ArrayList<ImageView>();

		viewPager = (ViewPager) findViewById(R.id.home_sliper);
		viewPager.setAdapter(mAdAdapter);// 设置填充ViewPager页面的适配器
		// 设置一个监听器，当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
	}
	private void initAds(){

		if(ads==null ){
			return;
		}
		imageViews.clear();
		// 初始化图片资源
		dots = new ArrayList<View>();
		
		View[] d = new View[7];
		d[0] = (View)(findViewById(R.id.v_dot0));
		d[1] = (View)(findViewById(R.id.v_dot1));
		d[2] = (View)(findViewById(R.id.v_dot2));
		d[3] = (View)(findViewById(R.id.v_dot3));
		d[4] = (View)(findViewById(R.id.v_dot4));
		d[5] = (View)(findViewById(R.id.v_dot5));
		d[6] = (View)(findViewById(R.id.v_dot6));
		
		for(int i=0;i<7;i++){
			d[i].setVisibility(View.GONE);
		}
		
		for (int i = 0;ads!=null&& i < ads.size()&&i<7; i++) {
			final ImageView imageView = new ImageView(this);
			final ProductAdEntity ad = ads.get(i);
			Drawable cachedImage = GoFunBuyUtils.asyncImageLoader.loadBigDrawable(ad.getImgPath(),new ImageCallback() {
				public void imageLoaded(Drawable imageDrawable,
						String imageUrl) {
					if(ad.getImg()==null){
						ad.setImg(imageDrawable);
						imageView.setImageDrawable(imageDrawable);	
					}else{
						imageView.setImageDrawable(ad.getImg());	
					}										
				}
			});
			if (cachedImage == null) {
				imageView.setImageResource(R.drawable.loading);
			} else {
				imageView.setImageDrawable(cachedImage);
			}	
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageViews.add(imageView);
			
			View v = new View(TabStoreGroup.group);
			
			d[i].setVisibility(View.VISIBLE);
			dots.add(d[i]);
			
		}
	
		mAdAdapter.notifyDataSetChanged();

		
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}

	@Override
	protected void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 3,
				TimeUnit.SECONDS);
		super.onStart();
	}
	@Override
	protected void onStop() {
		// 当Activity不可见的时候停止切换
		scheduledExecutorService.shutdown();
		super.onStop();
	}
	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				
				currentItem = (currentItem + 1) % imageViews.size();
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			
			currentItem = position;
			// tv_title.setText(titles[position]);
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.id_member_regist:
			startActivity(SubMemberRegistActivity.class);
			break;
		}
	}

	private void startActivity(Class<?> a) {
		// 要跳转的Activity
		// Log.v("名字", a.getSimpleName() + " " + a.getName());
		Intent intent = new Intent(this, a);
		// 把Activity转换成一个Window，然后转换成View
		Window w = TabStoreGroup.group.getLocalActivityManager()
				.startActivity(a.getSimpleName(), intent);
		View view = w.getDecorView();
		// 设置要跳转的Activity显示为本ActivityGroup的内容
		TabStoreGroup.group.setContentView(view);
		
	}
	private void startActivity(Class<?> a,Bundle b) {
		// 要跳转的Activity
		// Log.v("名字", a.getSimpleName() + " " + a.getName());
		Intent intent = new Intent(this, a);
		intent.putExtras(b);
		// 把Activity转换成一个Window，然后转换成View
		Window w = TabStoreGroup.group.getLocalActivityManager()
				.startActivity(a.getSimpleName(), intent);
		View view = w.getDecorView();
		// 设置要跳转的Activity显示为本ActivityGroup的内容
		TabStoreGroup.group.setContentView(view);
		
	}
    private class LoadTask extends AsyncTask<Void, Void, Void> { 
    	
        @Override  
        protected void onPreExecute() { 
        	if(!GoFunBuyUtils.isNetworkConnected(TabStoreGroup.group)){
    			Toast.makeText(TabStoreGroup.group, "网络状况不好！", 2000).show();
    			this.cancel(true);
    			return;
    		}
        	mProgressBar.setVisibility(View.VISIBLE);
        	mProductList.setVisibility(View.GONE);
        }            
        @Override  
        protected Void doInBackground(Void... params) {  
        	classes = getProductsClasses();
        	products = getProducts();

        	pro = new HashMap<String,List<ProductEntity>>();
        	
        	for(int i=0;classes!=null&&i<classes.size();i++){
        		List<ProductEntity> t =	new  ArrayList<ProductEntity>();
        		pro.put(classes.get(i).getName(), t);
        		
        		for(int j=0;products!=null&&j<products.size();j++){
        			if(products.get(j).getClassId().equals(classes.get(i).getId())){
        				t.add(products.get(j));
        			}
        		}
        	}
        	this.publishProgress();
        	
        	ads= getProductAd();
            return null;  
        }                   
          
        @Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
        	mProgressBar.setVisibility(View.GONE);
        	mProductList.setVisibility(View.VISIBLE);
        	
        	if(products!=null){
        		mAdapter.setDatas(products);
        		mAdapter.notifyDataSetChanged();
        	}
        	setClasses();
			super.onProgressUpdate(values);
		}
		@Override  
        protected void onPostExecute(Void result) {  
        			
    		initAds();   		
        }   
        @Override  
        protected void onCancelled() {  
        	
        }  
    }  
    private void setClasses(){
    	mClasses.removeAllViews();
    	for(int i=0;i<classes.size();i++){
    		TextView v = new TextView(this);
    		v.setSingleLine();
    		v.setText(classes.get(i).getName());
    		v.setTextColor(Color.WHITE);
    		v.setTextSize(15);
    		v.setPadding(10, 0, 10, 0);
    		v.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					resetTextColor();
					((TextView)v).setTextColor(getResources().getColor(R.color.Orange));
					mAdapter.setDatas(pro.get(((TextView)v).getText().toString()));
	        		mAdapter.notifyDataSetChanged();
				}    			
    		});
    		mClasses.addView(v);
    	}
    }
    private void resetTextColor(){
    	for(int i=0;i<mClasses.getChildCount();i++){
    		((TextView)mClasses.getChildAt(i)).setTextColor(Color.BLACK);
    	}
    }
}